import Util from "./util";
import { PT, NATIVE_COOKIE_KEY } from "./enums";

let subjectKey = 'PrestamoEx';
let domain = Util.env.isDev
  ? ""
  : `.${location.host.split(".").splice(-2).join(".")}`;

const _setExpires = (days) => {
  let date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  return date.toGMTString();
};

const _decode = (val) => JSON.parse(decodeURIComponent(val));

const base = {
  get: (key) => {
    let reg = new RegExp(`(^| )${key}=([^;]*)(;|$)`);
    let arr = document.cookie.match(reg);
    return arr ? decodeURI(arr[2]) : null;
  },
  set: (key, val, days, domain, path = "/", secure) => {
    let expires = false;
    if (!(Number(days) * 1)) {
      log(1, "cookie过期时间设置失败，请检查时间字段");
    } else {
      expires = _setExpires(days);
    }
    let secret = Util.isString(val) ? val : JSON.stringify(val);
    document.cookie = `${key}=${encodeURIComponent(secret)}${
      expires ? `;expires=${expires}` : ""
    }${path ? `;path=${path}` : ""}${domain ? `;domain=${domain}` : ""}${
      secure ? ";secure" : ""
    }`;
  },
  del: (name, domain, path, secure) => {
    base.set(name, "", -1, domain, path, secure);
  },
};

const subject = {
  get: () => base.get(subjectKey),
  set: (val) => base.set(subjectKey, val, 3, domain),
};

const custom = {
  get: (k) => base.get(k),
  set: (k, v) => base.set(k, v, 3, domain),
};

const user = {
  get: () => {
    try {
      return _decode(base.get(subjectKey + "_user_" + subject.get()));
    } catch (error) {
      log(1, "--tips：cache.js-- 未获取到用户信息，请检查");
      return null;
    }
  },
  set: (val) => {
    /**
     * 用户根据渠道隔离
     */
    subject.set(Util.getSubject(subject));
    base.set(subjectKey + "_user_" + subject.get(), val, 3, domain);
  },
  install: function (cb = () => {}, query = {}) {
    let index = query.pt || custom.get("plat") || 0;
    if (PT[index]) {
      log(`平台：${PT[index]}`);
      handleUserInfo(+index);
    } else {
      log(2, "请检查pt");
    }
    /**
     * 整合native设置的cookie
     */
    function handleNativeCache() {
      let temp = {};
      NATIVE_COOKIE_KEY.map((k) => (temp[k] = custom.get(k)));
      user.set(temp);
    }
    /**
     * 缓存用户信息
     * @param {环境来源} pt {环境来源枚举} PT
     */
    function handleUserInfo(pt) {
      switch (pt) {
        case 0:
          user.set({ cp_profile_id: "T6oQ5unA33CpszfuI8m0Ug==" });
          cb();
          break;
        case 1:
        case 2:
          handleNativeCache();
          cb();
          break;
        case 3:
          break;
        case 4:
          break;
        case 5:
          cb(true);
          break;
      }
    }
  },
};

export default {
  ...base,
  subject,
  custom,
  user,
};
